<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="search-form">
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleGenTable"
          v-hasPermi="['tool:gen:code']"
        >生成前后端代码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="openImportTable"
          v-hasPermi="['tool:gen:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEditTable"
          v-hasPermi="['tool:gen:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tool:gen:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="tableList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      :header-cell-style="{background:'#f8f8f9', color:'#606266', fontWeight: 'bold'}"
      :row-style="{height: '55px'}"
    >
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="表名称"
        align="center"
        prop="tableName"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="表描述"
        align="center"
        prop="tableComment"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="实体"
        align="center"
        prop="className"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div class="operation-buttons">
            <el-tooltip content="预览代码" placement="top">
              <el-button
                type="primary"
                size="mini"
                circle
                icon="el-icon-view"
                @click="handlePreview(scope.row)"
                v-hasPermi="['tool:gen:preview']"
              ></el-button>
            </el-tooltip>
            
            <el-tooltip content="编辑配置" placement="top">
              <el-button
                type="success"
                size="mini"
                circle
                icon="el-icon-edit"
                @click="handleEditTable(scope.row)"
                v-hasPermi="['tool:gen:edit']"
              ></el-button>
            </el-tooltip>
            
            <el-tooltip content="删除表" placement="top">
              <el-button
                type="danger"
                size="mini"
                circle
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['tool:gen:remove']"
              ></el-button>
            </el-tooltip>
            
            <el-divider direction="vertical"></el-divider>
            
            <el-tooltip content="同步表结构" placement="top">
              <el-button
                type="info"
                size="mini"
                circle
                icon="el-icon-refresh"
                @click="handleSynchDb(scope.row)"
                v-hasPermi="['tool:gen:edit']"
              ></el-button>
            </el-tooltip>
            
            <el-tooltip content="生成代码" placement="top">
              <el-button
                type="warning"
                size="mini"
                circle
                icon="el-icon-download"
                @click="handleGenTable(scope.row)"
                v-hasPermi="['tool:gen:code']"
              ></el-button>
            </el-tooltip>
            
            <el-tooltip content="查看表结构SQL" placement="top">
              <el-button
                type="info"
                size="mini"
                circle
                icon="el-icon-document"
                @click="handleViewSql(scope.row)"
                v-hasPermi="['tool:gen:sql']"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-row :gutter="20">
        <!-- 右侧代码展示 -->
        <el-col :span="24">
          <el-tabs v-model="preview.activeName">
            <el-tab-pane
              v-for="(value, key) in preview.data"
              :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
              :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
              :key="key"
            >
              <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value" v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
              <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-dialog>
    <import-table ref="import" @ok="handleQuery" />
    <!-- 表结构SQL对话框 -->
    <el-dialog :title="tableSql.title" :visible.sync="tableSql.open" width="80%" top="5vh" append-to-body class="sql-dialog">
      <div v-if="tableSql.content" class="sql-content">
        <pre><code class="hljs" v-html="highlightedCode(tableSql.content, 'sql')"></code></pre>
      </div>
      <div v-else class="empty-sql-message">
        <i class="el-icon-warning"></i>
        <p>未获取到表结构SQL数据，请检查后台日志</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-document-copy" v-clipboard:copy="tableSql.content" v-clipboard:success="clipboardSuccess">复制SQL</el-button>
        <el-button @click="tableSql.open = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTable, previewTable, delTable, genCode, synchDb, deleteCode, deleteFrontendCode, deleteBackendCode, getTableSql } from "@/api/tool/gen";
import importTable from "./importTable";
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));

export default {
  name: "Gen",
  components: { importTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 唯一标识符
      uniqueId: "",
      // 选中数组
      ids: [],
      // 选中表数组
      tableNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表数据
      tableList: [],
      // 日期范围
      dateRange: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tableName: undefined,
        tableComment: undefined
      },
      // 预览参数
      preview: {
        open: false,
        title: "代码预览",
        data: {},
        activeName: "domain.java"
      },
      // 表结构SQL参数
      tableSql: {
        open: false,
        title: "表结构SQL",
        content: ""
      }
    };
  },
  created() {
    this.getList();
  },
  activated() {
    const time = this.$route.query.t;
    if (time != null && time != this.uniqueId) {
      this.uniqueId = time;
      this.queryParams.pageNum = Number(this.$route.query.pageNum);
      this.getList();
    }
  },
  methods: {
    /** 查询表集合 */
    getList() {
      this.loading = true;
      listTable(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.tableList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 生成代码操作 */
    handleGenTable(row) {
      const tableNames = row.tableName || this.ids;
      if (tableNames == "") {
        this.$modal.msgError("请选择要生成的数据");
        return;
      }
      if (row.genType === "1") {
        // 添加合并模式参数
        const params = {
          mergeMode: row.mergeMode || "1" // 默认使用智能合并模式
        };
        genCode(tableNames, params).then(response => {
          this.$modal.msgSuccess("成功生成到自定义路径：" + row.genPath);
        });
      } else {
        this.$download.zip("/code/gen/batchGenCode?tables=" + tableNames, "hello.zip");
      }
    },
    /** 同步数据库操作 */
    handleSynchDb(row) {
      const tableName = row.tableName;
      this.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(function() {
        return synchDb(tableName);
      }).then(() => {
        this.$modal.msgSuccess("同步成功");
      }).catch(() => {});
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 预览按钮 */
    handlePreview(row) {
      previewTable(row.tableId).then(response => {
        this.preview.data = response.data;
        this.preview.open = true;
        this.preview.activeName = "domain.java";
      });
    },
    /** 高亮显示 */
    highlightedCode(code, key) {
      if (!code) {
        return '&nbsp;';
      }
      
      if (key === 'sql') {
        console.log("使用SQL语法高亮");
        try {
          const result = hljs.highlight('sql', code, true);
          return result.value || '&nbsp;';
        } catch (e) {
          console.error("SQL语法高亮出错:", e);
          return code;
        }
      }
      
      const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
      var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
      try {
        const result = hljs.highlight(language, code, true);
        return result.value || '&nbsp;';
      } catch (e) {
        console.error(`${language}语法高亮出错:`, e);
        return code;
      }
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tableId);
      this.tableNames = selection.map(item => item.tableName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleEditTable(row) {
      const tableId = row.tableId || this.ids[0];
      const tableName = row.tableName || this.tableNames[0];
      const params = { pageNum: this.queryParams.pageNum };
      this.$tab.openPage("修改[" + tableName + "]生成配置", '/tool/gen-edit/index/' + tableId, params);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tableIds = row.tableId || this.ids;
      this.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项?').then(function() {
        return delTable(tableIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 处理下拉菜单命令 */
    handleCommand(command) {
      const row = this.tableList.find(item => this.ids.includes(item.tableId)) || {};
      const tableName = row.tableName || this.tableNames[0];
      
      if (!tableName) {
        this.$modal.msgError("请选择要操作的数据");
        return;
      }
      
      switch (command) {
        case 'column':
          this.handlePreview(row);
          break;
        case 'zip':
          let data = { "tables": tableName };
          let config = { responseType: "blob", headers: { "Content-Type": "application/json" }};
          this.$confirm("是否确认生成代码?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            return this.$download.zip("/code/gen/batchGenCode", data, config);
          }).then(() => {
            this.$modal.msgSuccess("生成成功");
          }).catch(() => {});
          break;
        case 'delete':
          this.handleDeleteCode(row);
          break;
        case 'deleteFrontend':
          this.handleDeleteFrontendCode(row);
          break;
        case 'deleteBackend':
          this.handleDeleteBackendCode(row);
          break;
      }
    },
    /** 删除前端代码操作 */
    handleDeleteFrontendCode(row) {
      const tableName = row.tableName;
      this.$confirm('确认要删除已生成的前端代码吗？此操作不可逆，请谨慎操作！', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const params = {};
        deleteFrontendCode(tableName, params).then(() => {
          this.$modal.msgSuccess("前端代码删除成功");
        });
      }).catch(() => {});
    },
    /** 删除后端代码操作 */
    handleDeleteBackendCode(row) {
      const tableName = row.tableName;
      this.$confirm('确认要删除已生成的后端代码吗？此操作不可逆，请谨慎操作！', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const params = {};
        deleteBackendCode(tableName, params).then(() => {
          this.$modal.msgSuccess("后端代码删除成功");
        });
      }).catch(() => {});
    },
    /** 查看表结构SQL */
    handleViewSql(row) {
      const tableName = row.tableName;
      this.$modal.loading("正在获取表结构SQL...");
      console.log("请求获取表结构SQL，表名:", tableName);
      
      getTableSql(tableName).then(response => {
        this.$modal.closeLoading();
        console.log("获取SQL响应:", response);
        
        if (response.code === 200) {
          let sqlContent = "";
          
          // 检查data字段中是否有内容
          if (response.data && typeof response.data === "string") {
            console.log("从response.data获取SQL内容, 长度:", response.data.length);
            sqlContent = response.data;
          } 
          // 检查msg字段中是否有内容
          else if (response.msg && typeof response.msg === "string" && response.msg.includes("CREATE TABLE")) {
            console.log("从response.msg获取SQL内容, 长度:", response.msg.length);
            sqlContent = response.msg;
          }
          
          if (sqlContent) {
            this.tableSql.content = sqlContent;
          } else {
            console.error("响应成功但未找到SQL内容");
            this.$modal.msgWarning("未获取到表结构SQL数据");
            this.tableSql.content = "";
          }
        } else {
          console.error("响应失败:", response.msg);
          this.$modal.msgError(response.msg || "获取表结构SQL失败");
          this.tableSql.content = "";
        }
        
        this.tableSql.open = true;
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取表结构SQL请求异常:", error);
        this.$modal.msgError("获取表结构SQL失败: " + (error.message || error));
        this.tableSql.content = "";
        this.tableSql.open = true; // 即使失败也显示对话框，但内容为空
      });
    }
  }
};
</script>

<style scoped>
/* 表格整体样式 */
.el-table {
  margin-top: 20px;
  border-radius: 4px;
  overflow: hidden;
}

/* 表格边框采用浅色边框线 */
.el-table--border, .el-table--group {
  border: 1px solid #ebeef5;
}

.el-table td, .el-table th.is-leaf {
  border-bottom: 1px solid #ebeef5;
}

/* 表头使用淡灰色背景，字体加粗 */
.el-table th {
  background-color: #f8f8f9 !important;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

/* 数据行使用白底黑字，便于阅读 */
.el-table tr {
  background-color: #ffffff;
  color: #303133;
}

/* 行高固定，确保整齐 */
.el-table .el-table__row {
  height: 55px;
}

/* 鼠标悬停效果 */
.el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #f0f5ff !important;
}

/* 单元格内边距调整，确保内容对齐 */
.el-table .cell {
  padding-left: 15px;
  padding-right: 15px;
  line-height: 25px;
}

/* 斑马纹样式 */
.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

/* 当前选中行样式 */
.el-table__body tr.current-row>td {
  background-color: #ecf5ff !important;
}

/* 分页组件样式 */
.pagination-container {
  padding: 20px 0;
  text-align: center;
}

/* 预览对话框样式 */
.scrollbar {
  height: 85vh;
  overflow: hidden;
}

.scrollbar .el-tabs__content {
  overflow: auto;
  height: calc(85vh - 100px);
}

.scrollbar pre {
  margin: 15px 0;
  padding: 0;
}

.scrollbar code {
  padding: 20px;
  border-radius: 5px;
  overflow-x: auto;
  display: block;
  font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.7;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
  gap: 10px;
}

.operation-buttons .el-button {
  padding: 8px;
  margin: 0;
  transition: all 0.3s;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.operation-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.operation-buttons .el-divider--vertical {
  height: 24px;
  margin: 0 6px;
}

.operation-buttons .el-button--primary {
  background-color: #409EFF;
}

.operation-buttons .el-button--success {
  background-color: #67C23A;
}

.operation-buttons .el-button--danger {
  background-color: #F56C6C;
}

.operation-buttons .el-button--info {
  background-color: #909399;
}

.operation-buttons .el-button--warning {
  background-color: #E6A23C;
}

/* 目录树卡片样式 */
.directory-tree {
  height: 75vh;
  overflow: auto;
}

.directory-tree .el-tree {
  background-color: transparent;
}

.directory-tree .el-tree-node__content {
  height: 32px;
  line-height: 32px;
}

.custom-tree-node {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.custom-tree-node i {
  margin-right: 8px;
  color: #909399;
}

.custom-tree-node .el-icon-folder {
  color: #e6a23c;
}

.custom-tree-node .el-icon-document {
  color: #409eff;
}

/* 搜索表单样式 */
.search-form {
  padding: 18px 15px 5px;
  margin-bottom: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.search-form .el-form-item {
  margin-right: 20px;
  margin-bottom: 15px;
}

/* 顶部按钮组样式 */
.mb8 {
  margin-bottom: 15px;
}

.mb8 .el-col {
  padding-bottom: 10px;
}

.mb8 .el-button {
  padding: 8px 15px;
}

/* 整体容器样式 */
.app-container {
  padding: 20px;
}

.sql-dialog {
  /deep/ .el-dialog {
    margin-top: 5vh !important;
  }
  /deep/ .el-dialog__body {
    padding: 10px 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

.sql-content {
  pre {
    margin: 0;
    padding: 10px;
    background-color: #f8f8f8;
    border-radius: 5px;
    overflow-x: auto;
    white-space: pre-wrap;
    word-wrap: break-word;
  }
  
  code {
    font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
  }
}

.empty-sql-message {
  text-align: center;
  padding: 30px;
  color: #909399;
  
  i {
    font-size: 48px;
    margin-bottom: 10px;
  }
}
</style>
